package httpHandle

import (
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/wzh200x/webServer/config"
	"github.com/wzh200x/webServer/constants"
	"github.com/wzh200x/webServer/httpHandle/service"
	"github.com/wzh200x/webServer/middleware/response"
)

// PlatformLoginRequest 第三方平台登录请求结构
type PlatformLoginRequest struct {
	ThirdPlatformType int    `json:"thirdPlatformType" form:"thirdPlatformType" binding:"required"` // 平台类型
	AppId             string `json:"appId" form:"appId" binding:"required"`                         // 应用ID
	ThirdCode         string `json:"thirdCode" form:"thirdCode" binding:"required"`                 // 前端获取的平台登录code
	ThirdToken        string `json:"thirdToken" form:"thirdToken"`                                  // 前端获取的平台token
}

// PlatformLoginResponse 第三方平台登录响应结构
type PlatformLoginResponse struct {
	ThirdAccount    string `json:"thirdAccount"`    // 第三方账号
	ThirdSessionKey string `json:"thirdSessionKey"` // 平台返回的sessionkey
}

// HandlePlatformLogin 处理第三方平台登录
func HandlePlatformLogin(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	var loginReq PlatformLoginRequest
	if bindErr := c.ShouldBind(&loginReq); bindErr != nil {
		err(constants.ErrAuth, "无效的请求参数")
		return
	}

	// 根据平台类型调用不同的平台服务
	var thirdAccount, thirdSessionKey string
	var platformErr error
	var appId, appSecret, privateKey, publicKey string
	config := config.GetPlatformAppConfig(loginReq.ThirdPlatformType, loginReq.AppId)
	if config == nil {
		err(constants.ErrAuth, "不支持的平台类型")
		return
	}
	appId = config.AppID
	appSecret = config.AppSecret
	privateKey = config.PrivateKey
	publicKey = config.PublicKey
	packageName := config.PackageName

	// 调用平台登录服务
	thirdAccount, thirdSessionKey, platformErr = service.GetPlatformInfo(gconv.Int32(loginReq.ThirdPlatformType),
		appId, appSecret, privateKey, publicKey, packageName, loginReq.ThirdCode)

	if platformErr != nil {
		err(constants.ErrAuth, "获取平台信息失败: "+platformErr.Error())
		return
	}

	// 返回第三方账号和会话密钥
	success(PlatformLoginResponse{
		ThirdAccount:    thirdAccount,
		ThirdSessionKey: thirdSessionKey,
	})
}

type WxDecrptDataRequest struct {
	AppId         string `json:"appId" form:"appId" binding:"required"`                 // 应用ID
	SessionKey    string `json:"sessionKey" form:"sessionKey" binding:"required"`       // 会话密钥
	EncryptedData string `json:"encryptedData" form:"encryptedData" binding:"required"` // 加密数据
	IV            string `json:"iv" form:"iv" binding:"required"`                       // 向量
}

func HandleWxDecrptData(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)
	var req WxDecrptDataRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrAuth, "无效的请求参数")
		return
	}
	decrypted, e := service.WxDecrptData(req.AppId, req.SessionKey, req.EncryptedData, req.IV)
	if e != nil {
		err(constants.ErrAuth, "解密失败: "+e.Error())
		return
	}
	success(decrypted)
}
